<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
        #info {
                color: #fff;
                position: absolute;
                bottom: 10px;
                width: 100%;
                text-align: center;
                z-index: 100;
                display:block;
                
        }
</style>
<body style='font-family: Monospace; background-color: #000000; margin: 0px; overflow: hidden'>
<div style='color: #fff; position: absolute; bottom: 10px; width: 100%; text-align: center; z-index: 100; display:block;'>
        basic example for chromium-tango
</div>

<!-- TODO use your own version of the libraries -->
<script src="vendor/three.js/three.js"></script>
<script src="vendor/three.js/stats.min.js"></script>
<script src="vendor/three.js/VRControls.js"></script>
<script src="vendor/three.js/dat.gui.min.js"></script>

<script src="../../../vendor/chromium-tango/THREE.WebAR.js"></script>
        
<script>
	// array of functions for the rendering loop
	var onRenderFcts= [];
        
        
        var vrPointCloud, pointsObject;
        var vrDisplay = null
        var model;
        
        var MODEL_SIZE_IN_METERS = 0.1;
        
        // WebAR is currently based on the WebVR API so try to find the right
        // VRDisplay instance.
        if (navigator.getVRDisplays) {
                navigator.getVRDisplays().then(function(vrDisplays) {
                        if (vrDisplays && vrDisplays.length > 0) {
                                for (var i = 0; !vrDisplay && i < vrDisplays.length; i++) {
                                        vrDisplay = vrDisplays[i];
                                        if (vrDisplay.displayName !== "Tango VR Device") {
                                                vrDisplay = null;
                                        }
                                }
                        }
                        if (!vrDisplay) {
                                alert("No Tango WebAR VRDisplay found. Falling back to a video.");
                        }
                        init(vrDisplay);
                });
        } else {
                alert("No navigator.getVRDisplays. Falling back to a video.");
                init();
        }


        
        
        function init(vrDisplay) {

                //////////////////////////////////////////////////////////////////////////////
                //                add gui
                //////////////////////////////////////////////////////////////////////////////
                function GUI() {
                        this.showSeeThroughCamera = true;
                        this.continuousPicking = false;
                        this.showPointCloud = true;
                        this.pointsToSkip = 0;
                        return this;
                }
                // Initialize the dat.GUI.
                var datGUI = new dat.GUI();
                var gui = new GUI();
                datGUI.add(gui, "showSeeThroughCamera").name("Show seethrough camera");
                datGUI.add(gui, "continuousPicking").name("Continuous picking");
                datGUI.add(gui, "showPointCloud").onFinishChange(function(value) {
                        if (value) {
                                scene.add(pointsObject)
                        } else {
                                scene.remove(pointsObject);
                        }
                }).name("Show Point Cloud");
                datGUI.add(gui, "pointsToSkip", 0, 10).name("Points to kip");
                
                //////////////////////////////////////////////////////////////////////////////
                //                setup three.js
                //////////////////////////////////////////////////////////////////////////////
                // Create the 3D scene and camera
                var scene = new THREE.Scene();
                // Use the THREE.WebAR utility to create a perspective camera
                // suited to the actual see through camera parameters.
                var camera = THREE.WebAR.createVRSeeThroughCamera(vrDisplay, 0.01, 20);

                // Create the see through camera scene and camera
                var sceneOrtho = new THREE.Scene();
                var cameraOrtho = new THREE.OrthographicCamera( -1, 1, 1, -1, 0, 100 );

                //////////////////////////////////////////////////////////////////////////////
                //                Code Separator
                //////////////////////////////////////////////////////////////////////////////

                var cameraMesh = THREE.WebAR.createVRSeeThroughCameraMesh(vrDisplay, 'videos/sintel.webm');
                sceneOrtho.add(cameraMesh);
                onRenderFcts.push(function(){
                        // Make sure that the camera is correctly displayed depending on the
                        // device and camera orientations.
                        THREE.WebAR.updateCameraMeshOrientation(vrDisplay, cameraMesh);                        
                })

                //////////////////////////////////////////////////////////////////////////////
                //                create model
                //////////////////////////////////////////////////////////////////////////////
                // Create a cube model of 10 cm size.
                var geometry = new THREE.ConeBufferGeometry( MODEL_SIZE_IN_METERS / 2, MODEL_SIZE_IN_METERS)
                var material = new THREE.MeshLambertMaterial({
                        color: '0x888888'
                })
                model = new THREE.Mesh(geometry, material)
                // Apply a rotation to the model so it faces in the direction of the
                // normal of the plane when the picking based reorientation is done
                model.geometry.rotateZ(THREE.Math.degToRad(-90))
                model.position.set(0, 0, -2);
                scene.add(model);

                //////////////////////////////////////////////////////////////////////////////
                //                Code Separator
                //////////////////////////////////////////////////////////////////////////////
                var pointsMaterial = new THREE.PointsMaterial( 
                        { size: 0.01, vertexColors: THREE.VertexColors } 
                );
                pointsMaterial.depthWrite = false;
                var vrPointCloud = new THREE.WebAR.VRPointCloud(vrDisplay, true);


                pointsObject = new THREE.Points(vrPointCloud.getBufferGeometry(), pointsMaterial);
                // Points are changing all the time so calculating the frustum culling
                // volume is not very convenient.
                pointsObject.frustumCulled = false;
                pointsObject.renderDepth = 0;
                if( gui.showPointCloud === true )   scene.add(pointsObject);
                
                onRenderFcts.push(function(){
                        // Update the point cloud. Only if the point cloud will be shown the
                        // geometry is also updated.
                        vrPointCloud.update(gui.showPointCloud, gui.pointsToSkip, true);                        
                })

                //////////////////////////////////////////////////////////////////////////////
                //                Code Separator
                //////////////////////////////////////////////////////////////////////////////
                // Control the perspective camera using the VR pose.
                var vrControls = new THREE.VRControls(camera);
                onRenderFcts.push(function(){
                        vrControls.update();
                })
                // Add some lighting
                var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
                directionalLight.position.set( 0, 1, 0);
                scene.add( directionalLight );

                // Create the renderer
                var renderer = new THREE.WebGLRenderer();
                renderer.setPixelRatio( window.devicePixelRatio );
                renderer.setSize( window.innerWidth, window.innerHeight );

                // It is important to specify that the color buffer should not be
                // automatically cleared. The see through camera will render the whole
                // background.
                renderer.autoClear = false;
                document.body.appendChild( renderer.domElement );
                
                // Create a way to measure performance
                var stats = new Stats();
                document.body.appendChild( stats.dom );
                onRenderFcts.push(function(){
                        stats.update();
                })
                
                // Control the resizing of the window to correctly display the scene.
                window.addEventListener( 'resize', function onWindowResize() {
                        THREE.WebAR.resizeVRSeeThroughCamera(vrDisplay, camera);
                        renderer.setSize( window.innerWidth, window.innerHeight );
                }, false );
                
                //////////////////////////////////////////////////////////////////////////////
                //                picking
                //////////////////////////////////////////////////////////////////////////////
                var mousePosition = new THREE.Vector3(); // Avoid GC.

                // Wherever the user clicks in the screen, place the model.
                renderer.domElement.addEventListener("click", function(event) {
                        mousePosition.x = event.pageX / window.innerWidth;
                        mousePosition.y = event.pageY / window.innerHeight;
                        picking();
                });
                
                onRenderFcts.push(function(){
                        // If continuous picking is enabled, use the center of the screen
                        // to continuously pick.
                        if (gui.continuousPicking === false) return
                        mousePosition.x = 0.5;
                        mousePosition.y = 0.5;
                        picking();
                })
                
                function picking() {
                        if (vrDisplay) {
                                var pointAndPlane = 
                                vrDisplay.getPickingPointAndPlaneInPointCloud(mousePosition.x, mousePosition.y);
                                if (pointAndPlane) {
                                        // Orient and position the model in the picking point according
                                        // to the picking plane. The offset is half of the model size.
                                        THREE.WebAR.positionAndRotateObject3DWithPickingPointAndPlaneInPointCloud(
                                                pointAndPlane, model, MODEL_SIZE_IN_METERS / 2
                                        )
                                }
                                else {
                                        console.warn("Could not retrieve the correct point and plane.");
                                }
                        }
                }
                
                //////////////////////////////////////////////////////////////////////////////
                //                Code Separator
                //////////////////////////////////////////////////////////////////////////////
                onRenderFcts.push(function(){
                        // Render the see through camera scene
                        renderer.clear();
                        
                        if (gui.showSeeThroughCamera){                                
                                renderer.render( sceneOrtho, cameraOrtho );
                                // Render the perspective scene
                                renderer.clearDepth();
                        }
                        
                        
                        renderer.render( scene, camera );                        
                })
        }

        //////////////////////////////////////////////////////////////////////////////
        //                rendering loop
        //////////////////////////////////////////////////////////////////////////////       
	// run the rendering loop
	var lastTimeMsec= null
	requestAnimationFrame(function animate(nowMsec){
		// keep looping
		requestAnimationFrame( animate );
		// measure time
		lastTimeMsec	= lastTimeMsec || nowMsec-1000/60
		var deltaMsec	= Math.min(200, nowMsec - lastTimeMsec)
		lastTimeMsec	= nowMsec
		// call each update function
		onRenderFcts.forEach(function(onRenderFct){
			onRenderFct(deltaMsec/1000, nowMsec/1000)
		})
	})
</script></body>
